import 'package:cat_eye/base/base_chang_notifier.dart';
import 'package:cat_eye/http/http_manager.dart';
import 'package:cat_eye/util/loading_state_widget_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/*
* @Package: base
* @ClassName: base_view_model
* @Author: szj
* @CreateDate: 8/2/21 10:19 AM
* TODO 上拉加载 下拉刷新的 State
*/
abstract class BaseRefreshViewModel extends BaseChangNotifier {
  //上拉加载/下拉刷新控制器
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  //Http数据
  String get httpUrl;

  //上拉刷新需要的数据
  String get httpLoadMoreUrl;

  //默认上啦加载
  bool get isLoadMore => true;
  //默认下拉刷新
  bool get isRefresh => true;

  void successJsonData(dynamic json);

  // 获取数据
  void refresh() async {
    await HttpManager.requestHttpData(
      httpUrl,
      onSuccess: (json) {
        //请求成功
        type = LoadingWidget.DONG;

        //当下一个接口请求回来时候,关闭刷新按钮
        refreshController.refreshCompleted();
        refreshController.footerMode.value = LoadStatus.canLoading;

        //获取返回成功Json串
        successJsonData(json);
      },
      onFail: (e) {
        //请求失败
        type = LoadingWidget.ERROR;
      },
      complete: () => notifyListeners(),
    );
  }

  //上啦加载
  void loadMore() async {
    await HttpManager.requestHttpData(
      httpLoadMoreUrl,
      onSuccess: (json) {
        //请求成功
        type = LoadingWidget.DONG;

        //重新加载
        refreshController.loadComplete();
        //获取返回成功Json串
        successJsonData(json);
      },
      onFail: (e) {
        //请求失败
        type = LoadingWidget.ERROR;
        refreshController.loadFailed();
      },
      complete: () => notifyListeners(),
    );
  }

  //错误重试
  void retry() {
    refresh();
    notifyListeners();
  }
}
